<?php

/*
 *  This file is part of Urd.
 *
 *  Urd is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *  Urd is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program. See the file "COPYING". If it does not 
 *  exist, see <http://www.gnu.org/licenses/>.
 * 
 * $LastChangedDate: 2009-01-03 23:44:12 +0100 (Sat, 03 Jan 2009) $
 * $Rev: 410 $
 * $Author: gavinspearhead $
 * $Id: do_functions.php 410 2009-01-03 22:44:12Z gavinspearhead $
 */

if (!defined('ORIGINAL_PAGE')) die('This file cannot be accessed directly.');

$pathrss = realpath(dirname(__FILE__));

//$magpie_cache_dir =  set_magpie_cache_dir();
// caching is needed
//define('MAGPIE_CACHE_ON', 1);
// and here we store the cached data: --> make sure it exists in installer TODO
//define ('MAGPIE_CACHE_DIR', $magpie_cache_dir);

require_once "$pathrss/../functions/libs/magpierss/rss_fetch.inc";


function make_rss_setid($rss_url, $link)
{
	return md5($rss_url . $link);
}


function check_link(DatabaseConnection $db, $id, $link)
{
	// check if a link already exists in the db for that rss feed
	$db->escape($link, TRUE);
	$db->escape($id, TRUE);
	$qry = "SELECT \"setid\" FROM rss_sets WHERE \"nzb_link\" = $link AND \"rss_id\" = $id";
	
	$res = $db->execute_query($qry);
	if (!is_array($res))
		return FALSE;
	else 
		return $res[0]['setid'];
}


function get_size_from_description($description)
{
	$rv = preg_match("/size\s*:?\s*([\d.,]+)\s([kmgt]b?)*/i", $description, $matches);
	if ($rv >= 0) { // we found a size
		$size = isset($matches[1]) ? trim($matches[1]) : 0;
		$size = str_replace(',', '.', $size);
		if (is_numeric($size)) {
			$order = strtolower(isset($matches[2]) ? trim( $matches[2]) : '');
			if (isset($order[0])) {
				switch ($order[0]) {
				case 'k': $size *= 1024; break;
				case 'm': $size *= 1024 * 1024; break;
				case 'g': $size *= 1024 * 1024 * 1024; break;
				case 't': $size *= 1024 * 1024 * 1024 * 1024; break;
				}
			}
			$size = floor($size);
		} else 
			$size = 0;
	} else
		$size = 0;
	return $size;
}


function update_rss_set(DatabaseConnection $db, $setid, $title, $timestamp, $description, $summary)
{
	assert(is_numeric($timestamp) && $title != '');
	$title = html_entity_decode($title, ENT_COMPAT, 'UTF-8');
	$description = html_entity_decode($description, ENT_COMPAT, 'UTF-8');
	$summary = html_entity_decode($summary, ENT_COMPAT, 'UTF-8');
	$size = get_size_from_description($description);
	$db->escape($setid, TRUE);
	$db->update_query('rss_sets', array('setname', 'timestamp', 'description', 'summary', 'size'), 
			array($title, $timestamp, $description, $summary, $size), "\"setid\" = $setid");
}


function insert_rss_set(DatabaseConnection $db, $rss_id, $link, $title, $timestamp, $description, $summary)
{
	assert(is_numeric($rss_id) && is_numeric($timestamp) && $link != '' && $title != '');
	$title = html_entity_decode($title, ENT_COMPAT, 'UTF-8');
	$description = html_entity_decode($description, ENT_COMPAT, 'UTF-8');
	$summary = html_entity_decode($summary, ENT_COMPAT, 'UTF-8');
	$size = get_size_from_description($description);

	$db->insert_query('rss_sets', array('setid', 'rss_id', 'setname', 'nzb_link', 'timestamp', 'description', 'summary', 'size'), 
		array(md5($link), $rss_id, $title, $link, $timestamp, $description, $summary, $size));
}


function update_feedcount(DatabaseConnection $db, $rss_id)
{
	assert(is_numeric($rss_id));
	$db->escape($rss_id, TRUE);
	$sql = "UPDATE rss_urls SET \"feedcount\"= (SELECT COUNT(\"id\") FROM rss_sets WHERE \"rss_id\"= $rss_id) WHERE \"id\"=$rss_id";
	$db->execute_query($sql);
}


function rss_update(DatabaseConnection $db, array $rss_info)
{
	echo_debug_function(DEBUG_MAIN, __FUNCTION__);
	$newcnt = $updcnt = 0;
 	$rss_id = $rss_info['id'];
	$url = $rss_info['url'];
	$username = $rss_info['username'];
	$password = $rss_info['password'];
	$expire = $rss_info['expire']; // in days
	$expire *= 24 * 3600; // in seconds now
	$now = time();
	$expire_time = $now - $expire;
	$rss = fetch_rss($url, get_magpie_cache_dir(), $username, $password);
	
	foreach($rss->items as $item) {
		if (!isset($item['link']) || !isset($item['title'])) 
			continue;
		
		$link = $item['link'];
		$title = $item['title'];
		$timestamp = isset($item['date_timestamp']) ? $item['date_timestamp'] : time();
		$description = utf8_encode(isset ($item['description']) ? $item['description'] : $title);
		$summary = utf8_encode(isset($item['summary'])? $item['summary'] : $title);
		if ($timestamp >= $expire_time) {
			$id = check_link($db, $rss_id, $link);
			if ($id === FALSE) {// if it doesn't exist, add it
				insert_rss_set($db, $rss_id, $link, $title, $timestamp, $description, $summary);
				$newcnt++;
			} else  {
				update_rss_set($db, $id, $title, $timestamp, $description, $summary);
				$updcnt++;
			}

		}
	}
	echo_debug("Updated $updcnt sets; added $newcnt sets", DEBUG_SERVER);
	update_feedcount($db, $rss_id);
}


function purge_rss(DatabaseConnection $db, $rss_id, $dbid=NULL)
{
	echo_debug_function(DEBUG_MAIN, __FUNCTION__);
	assert (is_numeric($rss_id));
	$orss_id = $rss_id;
	$rss_info = get_rss_info($db, $rss_id);
    $type = USERSETTYPE_RSS;
    $db->escape($rss_id, TRUE);

	$qry = "SELECT count(\"id\") AS cnt FROM rss_sets WHERE \"rss_id\" = $rss_id ";
	$res = $db->execute_query($qry);
	$cnt = $res[0]['cnt'];

	$sql = "DELETE FROM usersetinfo WHERE \"setID\" in (SELECT \"setid\" FROM rss_sets WHERE \"rss_id\" = $rss_id) AND \"type\" = '$type' ";
    $res = $db->execute_query($sql);

    if ($dbid !== NULL)
        update_queue_status ($db, $dbid, NULL, 0, 30);

	$sql = "DELETE FROM extsetdata WHERE \"setID\" in (SELECT \"setid\" FROM rss_sets WHERE \"rss_id\" = $rss_id) AND \"type\" = '$type' ";
    $res = $db->execute_query($sql);

    if ($dbid !== NULL)
        update_queue_status ($db, $dbid, NULL, 0, 60);

	$qry = "DELETE FROM rss_sets WHERE \"rss_id\" = $rss_id ";
    $res = $db->execute_query($qry);
   
    if ($dbid !== NULL)
        update_queue_status ($db, $dbid, NULL, 0, 90);

    update_feedcount($db, $orss_id);
    $db->execute_query("UPDATE rss_urls SET \"extset_update\" = '0' WHERE \"id\" = $rss_id");
	delete_cache_entry($rss_info['url'], get_magpie_cache_dir());
    if ($dbid !== NULL)
        update_queue_status ($db, $dbid, NULL, 0, 100);
	return $cnt;
}

/*
function expire_rss_2(DatabaseConnection $db, $rss_id, $dbid)
{
    echo_debug_function(DEBUG_MAIN, __FUNCTION__);
    assert(is_numeric($rss_id));
    $orss_id = $rss_id;
    $cnt = 0;
    $rss_info = get_rss_info($db, $rss_id);
    $expire = $rss_info['expire'];
    $expire *= 24 * 3600; // in seconds now
    $expire = time() - $expire;
    $type = USERSETTYPE_RSS;
    $marking_on = MARKING_ON;
    $db->escape($rss_id, TRUE);
    $db->escape($expire, TRUE);
    $prefs = load_config($db);
    if ($prefs['keep_interesting'] )
        $keep_int  = " AND \"setid\" NOT IN ( SELECT \"setID\" FROM usersetinfo WHERE \"type\" =  '$type' AND \"statusint\" = '$marking_on') ";
    else 
        $keep_int = '';
    $qry = "SELECT count(\"id\") AS cnt FROM rss_sets WHERE \"rss_id\" = $rss_id AND \"timestamp\" < $expire $keep_int";
    $res = $db->execute_query($qry);
    $cnt = $res[0]['cnt'];
    update_queue_status ($db, $dbid, NULL, 0, 1);

    if ($prefs['keep_interesting'] )
        $keep_int = " AND  \"statusint\" != '$marking_on' ";
    else 
        $keep_int = '';

    $sql = "DELETE FROM usersetinfo WHERE \"setID\" IN (SELECT \"setid\" FROM rss_sets WHERE \"rss_id\" = $rss_id AND \"timestamp\" < $expire) AND \"type\" = '$type' $keep_int";
    $res = $db->execute_query($sql);

    update_queue_status ($db, $dbid, NULL, 0, 30);
    if ($prefs['keep_interesting'] )
        $keep_int  = " AND \"setID\" NOT IN ( SELECT \"setID\" FROM usersetinfo WHERE \"type\" =  '$type' AND \"statusint\" = '$marking_on') ";
    else 
        $keep_int = '';

    $sql = "DELETE FROM extsetdata WHERE \"setID\" IN (SELECT \"setid\" FROM rss_sets WHERE \"rss_id\" = $rss_id AND \"timestamp\" < $expire) AND \"type\" = '$type' $keep_int";
    $res = $db->execute_query($sql);

    update_queue_status ($db, $dbid, NULL, 0, 60);
    if ($prefs['keep_interesting'] )
        $keep_int  = " AND \"setid\" NOT IN ( SELECT \"setID\" FROM usersetinfo WHERE \"type\" =  '$type' AND \"statusint\" = '$marking_on')  ";
    else 
        $keep_int = '';

    $qry = "DELETE FROM rss_sets WHERE \"rss_id\" = $rss_id AND \"timestamp\" < $expire $keep_int";
    $res = $db->execute_query($qry);

    update_queue_status ($db, $dbid, NULL, 0, 90);

    echo_debug("Deleted {$cnt} sets", DEBUG_DATABASE);
    update_feedcount($db, $orss_id);
    update_queue_status ($db, $dbid, NULL, 0, 100);
    return $cnt; 
} */



function expire_rss(DatabaseConnection $db, $rss_id, $dbid)
{
    echo_debug_function(DEBUG_MAIN, __FUNCTION__);
    assert(is_numeric($rss_id));
    $orss_id = $rss_id;
    $cnt = 0;
    $rss_info = get_rss_info($db, $rss_id);
    $expire = $rss_info['expire'];
    $expire *= 24 * 3600; // in seconds now
    $expire = time() - $expire;
    $type = USERSETTYPE_RSS;
    $marking_on = MARKING_ON;
    $db->escape($rss_id, TRUE);
    $db->escape($expire, TRUE);
    $prefs = load_config($db);
    if ($prefs['keep_interesting'] )
        $keep_int  = " AND \"setid\" NOT IN ( SELECT \"setID\" FROM usersetinfo WHERE \"type\" =  '$type' AND \"statusint\" = '$marking_on') ";
    else 
        $keep_int = '';
    
    $qry = "SELECT count(\"id\") AS cnt FROM rss_sets WHERE \"rss_id\" = $rss_id AND \"timestamp\" < $expire $keep_int";
    $res = $db->execute_query($qry);
    if ($res === FALSE)
        $cnt = 0 ;
    else 
        $cnt = $res[0]['cnt'];
    update_queue_status ($db, $dbid, NULL, 0, 1);
// first delete everything we want to remove  
    $qry = "DELETE FROM rss_sets WHERE \"rss_id\" = $rss_id AND \"timestamp\" < $expire $keep_int";
    $res = $db->execute_query($qry);
    update_queue_status ($db, $dbid, NULL, 0, 30);

    // then rm all usersetinfo that has a set id of a set we already removed
    $sql = "DELETE FROM usersetinfo WHERE \"setID\" NOT IN (SELECT \"setid\" FROM rss_sets ) AND \"type\" = '$type' ";
    $res = $db->execute_query($sql);

    update_queue_status ($db, $dbid, NULL, 0, 60);
   // ditto extsetinfo
    $sql = "DELETE FROM extsetdata WHERE \"setID\" NOT IN (SELECT \"setid\" FROM rss_sets) AND \"type\" = '$type' ";
    $res = $db->execute_query($sql);

    update_queue_status ($db, $dbid, NULL, 0, 90);

    echo_debug("Deleted {$cnt} sets", DEBUG_DATABASE);
    update_feedcount($db, $orss_id);
    update_queue_status ($db, $dbid, NULL, 0, 100);
    return $cnt; 
} 
 

?>
